import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:flutter_sound/public/flutter_sound_player.dart';
import 'package:flutter_sound/public/tau.dart';
import 'package:flutter_weixin/app/modules/wechat_content/controllers/wechat_content_controller.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_view.dart';
import 'package:path_provider/path_provider.dart';
import 'package:web_socket_channel/io.dart';

/**
 * 按住说话
 */
class HoldToTalkWidget extends GetView<WechatContentController> {
  StreamSubscription? _mRecordingDataSubscription;

  Future<IOSink> createFile() async {
    var tempDir = await getTemporaryDirectory();
    controller.mPath.value = '${tempDir.path}/flutter_sound_example.pcm';
    var outputFile = File(controller.mPath.value);
    if (outputFile.existsSync()) {
      await outputFile.delete();
    }
    return outputFile.openWrite();
  }

  Future<void> record() async {
    var sink = await createFile();
    var recordingDataController = StreamController<Food>();
    _mRecordingDataSubscription =
        recordingDataController.stream.listen((buffer) {
          if (buffer is FoodData) {
            sink.add(buffer.data!);
            Future.delayed(Duration(milliseconds: 40), () async {
              // print("长度-----${buffer.data!.length}");
                  controller.channel?.sink.add(buffer.data!);
            });
          }
        });

    await controller.myRecorder.startRecorder(
      toStream: recordingDataController.sink,
      codec: Codec.pcm16,
      numChannels: 1,
      sampleRate: 44000,
    );
  }

  Future<void> stopRecorder() async {
    await controller.myRecorder.stopRecorder();
    controller.channel!.sink.add('{"end": true}');
    if (_mRecordingDataSubscription != null) {
      await _mRecordingDataSubscription!.cancel();
      _mRecordingDataSubscription = null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onLongPressStart: (LongPressStartDetails details) async {
        // 开始录音
        record().then((value) {
          // 开始转化成文字
          controller.currentTs.value = controller.getTs();
          String baseString = controller.appid + controller.currentTs.value;
          String md5baseString =
          md5.convert(utf8.encode(baseString)).toString();

          var key = utf8.encode(controller.appkey);

          Hmac mac = new Hmac(sha1, key);
          Digest sha1Result = mac.convert(utf8.encode(md5baseString));
          String sing = base64Encode(sha1Result.bytes);
          print(sing);

          String url = 'wss://rtasr.xfyun.cn/v1/ws?appid=${controller
              .appid}&ts=${controller.currentTs.value}&signa=${sing}';

          controller.channel = IOWebSocketChannel.connect(Uri.parse(url));
          controller.channel?.stream.listen((message) {
            print("-----");
            print(message);
          });
        });
        controller.voiceHeight.value = 200;
        controller.voicePositioned.value =
            controller.voicePositioned.value + 200;
        controller.startOffset = details.globalPosition;
        controller.isLongPress.value = true;
      },
      onLongPressMoveUpdate: (LongPressMoveUpdateDetails details) {
        var dx =
            (controller.startOffset?.dx ?? 0.0) - details.globalPosition.dx;
        var dy =
            (controller.startOffset?.dy ?? 0.0) - details.globalPosition.dy;
        if (dx >= 22 && dy >= 80) {
          controller.longPressState.value = 1;
          controller.width.value = 100;
          controller.voiceFrameHeight.value = 44.0;
          controller.color.value = Colors.red;
          controller.left.value = 10;
          controller.left.refresh();
        } else if (dx <= 22 && dy >= 80) {
          // //start 语音转文字
          // print(controller.getTs());
          //end
          controller.longPressState.value = 2;
          controller.width.value = Get.width - 20;
          controller.voiceFrameHeight.value = 80;
          controller.color.value = Color(0xFFa7e678);
          controller.left.value = 10;
          controller.left.refresh();
        } else {
          controller.voiceFrameHeight.value = 44.0;
          controller.longPressState.value = 0;
          controller.width.value = (Get.width / 2);
          controller.left.value = (Get.width / 2) / 2;
          controller.color.value = Color(0xFFa7e678);
        }
      },
      onLongPressEnd: (LongPressEndDetails details) async {
        // 定制录音
        await stopRecorder();

        //直接可以播放
        await controller.myPlayer.startPlayer(
          fromURI: controller.mPath.value,
          codec: Codec.pcm16,
          numChannels: 1,
          sampleRate: 44000,
        );
        // controller.myPlayer

        controller.voiceFrameHeight.value = 44.0;
        controller.longPressState.value = 0;
        controller.voiceHeight.value = 0.0;
        controller.color.value = Color(0xFFa7e678);
        controller.voicePositioned.value = 200;
        controller.isLongPress.value = false;
        controller.startOffset = null;
        controller.width.value = (Get.width / 2);
        controller.left.value = (Get.width / 2) / 2;
      },
      child: Container(
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(7)),
        constraints: BoxConstraints(
          maxHeight: 37,
        ),
        child: Container(
          alignment: Alignment.center,
          child: new Text("按住说话"),
        ),
      ),
    );
  }
}
